import { autoUpdater } from 'electron-updater'
import { ipcMain, BrowserWindow } from 'electron'

const downloadedWins:BrowserWindow[] =[];
let downloadWin:BrowserWindow|null=null;
let judgeRs={}
let isDownloading=false;
autoUpdater.setFeedURL('http://192.168.31.212:8888/updater/')
export function checkUpdate(win: BrowserWindow): void {
  downloadedWins.push(win);
  win.on('closed', () => {
    downloadedWins.splice(downloadedWins.indexOf(win), 1)
  })
  autoUpdater.forceDevUpdateConfig = true //开发环境下强制更新
  autoUpdater.autoDownload = false; // 自动下载
  autoUpdater.autoInstallOnAppQuit = true; // 应用退出后自动安装
}

export function setDownloadWin(win: BrowserWindow): void {
    downloadWin = win;
    downloadedWins.push(win);
    win.on('closed', () => {
      downloadedWins.splice(downloadedWins.indexOf(win), 1)
    })
}

autoUpdater.on('update-available', (info) => {
    console.log('有新版本需要更新',info);
    judgeRs={
        success:true,
        needUpdate:true,
        msg:'有新版本需要更新',
        version:info.version
    }
});
autoUpdater.on('update-not-available', () => {
    console.log('无需更新');
    judgeRs={
        success:true,
        needUpdate:false,
        msg:'无需更新'
    }
});

// 监听渲染进程的 install 事件，触发退出应用并安装
ipcMain.handle('application:install-update', () => autoUpdater.quitAndInstall());

ipcMain.handle('application:check-update',async ()=>{
    try {
        if(isDownloading){
            return {
                success:true,
                isDownloading:true,
                msg:'正在下载中，请稍后'
            }
        }else{
            const res = await autoUpdater.checkForUpdatesAndNotify()
            console.log('judge',res)
            //如果check结果正常，则使用上面监听构造的judgeRs
            return judgeRs
        }

    }catch (_e){
      console.log('check error', _e)
    //    check报错
        judgeRs = {
            success: false,
            msg: '没有更新包'
        }
        return judgeRs
    }
})
autoUpdater.on('download-progress', (prog) => {
    const speed=prog.bytesPerSecond / 1000000>1?Math.ceil(prog.bytesPerSecond / 1000000)+'M/s':Math.ceil(prog.bytesPerSecond / 1000)+'K/s'
    downloadWin?.webContents.send('application:download-progress',  {
        speed, // 网速
        percent: Math.ceil(prog.percent), // 百分比
    });
    isDownloading=true

});
autoUpdater.on('update-downloaded', () => {
    isDownloading=false
    downloadedWins.forEach((win) => {
      win?.webContents.send('application:update-downloaded');
    })
});

/*监听渲染进程指令，执行更新*/
ipcMain.on('application:update-download', () => {
    autoUpdater.autoDownload = true;
    autoUpdater.checkForUpdates();
})


// autoUpdater.
